#!/bin/sh
# Starts the Qai Space server if it is not running, then opens it in the browser. Data lives in ~/Library/Application Support/Qai Space.
DIR=$(cd "$(dirname "$0")/.." && pwd)
DATA="$HOME/Library/Application Support/Qai Space"
PORT=8790
URL="http://127.0.0.1:$PORT"
mkdir -p "$DATA"
if ! curl -s -o /dev/null "$URL/"; then
  if [ ! -f "$DATA/qai.db" ]; then
    # The app refuses passwords shorter than 10 characters (MIN_PASSWORD_LEN in src/kernel/auth.rs), so ask until it fits.
    ASK="Welcome to Qai Space. Choose a password of at least 10 characters for the administrator (admin@qai.local). You will use it to sign in."
    while :; do
      PW=$(osascript -e "text returned of (display dialog \"$ASK\" default answer \"\" with hidden answer with title \"Qai Space\")") || exit 0
      [ ${#PW} -ge 10 ] && break
      ASK="That password is too short. Choose one of at least 10 characters for the administrator (admin@qai.local)."
    done
    export QAI_ADMIN_PASSWORD="$PW"
  fi
  QAI_PUBLIC_URL="$URL" nohup "$DIR/Resources/qai" --data "$DATA" serve --bind "127.0.0.1:$PORT" >> "$DATA/server.log" 2>&1 &
  for i in $(seq 1 40); do curl -s -o /dev/null "$URL/" && break; sleep 0.5; done
fi
open "$URL"
